package fti.uksw.ruang.dialog;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TimePicker;

public class DateTimeDialog extends DialogFragment {

	public static final int DATEDIALOG = 10;
	public static final int TIMEDIALOG = 20;

	static Context mContext;
	static Calendar mCalendar;
	static DateTimeDialogFragmentListener sListener;

	public static DateTimeDialog newInstance(Context context,
			int titleResource, Calendar date) {
		DateTimeDialog dialog = new DateTimeDialog();

		mContext = context;
		mCalendar = date;

		Bundle args = new Bundle();
		args.putInt("title", titleResource);
		dialog.setArguments(args);
		return dialog;
	}

	public Dialog onCreateDialog(Bundle savedInstanceStatce) {
		int title = getArguments().getInt("title");
		switch (title) {

		case DATEDIALOG:

			return new DatePickerDialog(mContext, dateSetListener,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH),
					mCalendar.get(Calendar.DAY_OF_MONTH));

		case TIMEDIALOG:
			return new TimePickerDialog(mContext, timeSetListener,
					mCalendar.get(Calendar.HOUR_OF_DAY),
					mCalendar.get(Calendar.MINUTE), false);
		default:
			return null;
		}
	}

	public interface DateTimeDialogFragmentListener {
		public void dateDialogFragmentDateTimeSet(Calendar calendar);
	}

	public void setDateTimeDialogFragmentListener(
			DateTimeDialogFragmentListener listener) {
		sListener = listener;
	}

	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mCalendar.set(year, monthOfYear, dayOfMonth);
			sListener.dateDialogFragmentDateTimeSet(mCalendar);
		}
	};

	public TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			mCalendar.set(Calendar.MINUTE, minute);
			sListener.dateDialogFragmentDateTimeSet(mCalendar);
		}
	};
}
